#include <QBoxLayout>
#include <QGroupBox>

#include "OperationWidget.h"
#include "OperandDisplay.h"
#include "BinaryOpWidget.h"

OperationWidget::OperationWidget(QWidget * parent)
    : QWidget(parent)
{
    QVBoxLayout *topLayout = new QVBoxLayout(this);

    mCBoxEnAsciiView = new QCheckBox("Show ASCII value");
    mCBoxEnBitView = new QCheckBox("Show Bit Editor");
    mCBoxEnAsciiView->hide();
    mCBoxEnBitView->hide();

    QHBoxLayout *viewLayout = new QHBoxLayout();
    viewLayout->addWidget(mCBoxEnAsciiView);
    viewLayout->addWidget(mCBoxEnBitView);
    viewLayout->insertStretch(-1);

    QGroupBox *boxArr0 = new QGroupBox("Operand 0");
    QGroupBox *boxArr1 = new QGroupBox("Operand 1");
    QGroupBox *boxOp0 = new QGroupBox("Operation");
    QGroupBox *boxRes0 = new QGroupBox("Result");

    QVBoxLayout *boxArr0Layout = new QVBoxLayout(boxArr0);
    QVBoxLayout *boxArr1Layout = new QVBoxLayout(boxArr1);
    QVBoxLayout *boxOpLayout = new QVBoxLayout(boxOp0);
    QVBoxLayout *boxResLayout = new QVBoxLayout(boxRes0);

    boxArr0Layout->setContentsMargins(5, 0, 5, 5);
    boxArr1Layout->setContentsMargins(5, 0, 5, 5);
    boxOpLayout->setContentsMargins(5, 0, 5, 5);
    boxResLayout->setContentsMargins(5, 0, 5, 5);

    OperandDisplay *d0 = new OperandDisplay();
    OperandDisplay *d1 = new OperandDisplay();
    opWidget = new BinaryOpWidget(this, d0->getArray(), d1->getArray());
    resultDisplay = new OperandDisplay(0, false);

    boxArr0Layout->addWidget(d0);
    boxArr1Layout->addWidget(d1);
    boxOpLayout->addWidget(opWidget);
    boxOpLayout->setContentsMargins(0, 0, 0, 5);
    boxResLayout->addWidget(resultDisplay);

    topLayout->addLayout(viewLayout);
    topLayout->addWidget(boxArr0);
    topLayout->addWidget(boxOp0);
    topLayout->addWidget(boxArr1);
    topLayout->addWidget(boxRes0);

    topLayout->insertStretch(-1);

    connect(d0, SIGNAL(valueChanged()), this, SLOT(valueChangedSlot()));
    connect(d1, SIGNAL(valueChanged()), this, SLOT(valueChangedSlot()));
    connect(opWidget, SIGNAL(operationChanged()), this, SLOT(valueChangedSlot()));
    connect(mCBoxEnAsciiView, SIGNAL(clicked()), this, SLOT(viewSettingsChanged()));
    connect(mCBoxEnBitView, SIGNAL(clicked()), this, SLOT(viewSettingsChanged()));
}

void OperationWidget::valueChangedSlot()
{
   bool sgnd = resultDisplay->getArray()->isSigned();
   *(resultDisplay->getArray()) = opWidget->operate();
   resultDisplay->getArray()->setSigned(sgnd);
   resultDisplay->updateView();
}

void OperationWidget::viewSettingsChanged()
{

}
